import type { Plugin } from 'vite';
// import { getConfig } from './config';
import { EXT_NAME } from './constant';
import { init, hotReloadFn } from './tools/hotReloadFn';
import { getConfig, setConfig, readConfigFile } from './config';

export default function Autocss(): Plugin {
    const autocssConfig = readConfigFile();

    return {
        // 插件名称
        name: 'vite-plugin-autocss',

        // pre 会比 post 先执行
        enforce: 'pre',

        // 指明仅在 'build/serve' 环境 调用
        apply: 'serve',

        config(config, { command }) {
            // console.log('这里是config钩子');
            setConfig(autocssConfig);
            init();
            return config;
        },

        configResolved(resolvedConfig) {
            // console.log('这里是configResolved钩子');
        },

        configureServer(server) {
            // console.log('这里是configureServer钩子');
        },

        transformIndexHtml(html) {
            // console.log('这里是transformIndexHtml钩子');
        },

        transform(code, id) {
            // console.log('这里是热更新结束后的转译钩子');
            // console.log(code);
        },

        async handleHotUpdate({ file, read }) {
            // console.log('这里是修改代码热更新监听内容');
            // const [, extName] = file.match(/(?<=\.)([\w\d]+)$/);
            // console.log(file.match(/(?<=\.)([\w\d]+)$/));
            // console.log(await read());
            const str = await read();
            // 匹配修改的class
            // const classNameList = str.match(/(?:(?<=class=(["']))[\s\S]*?(?=\1))|((?<=class={)[\s\S]*?(?=}))/gi);
            // console.log(classNameList, '匹配的class');
            const matchLetter: RegExpMatchArray | null = file.match(/(?<=\.)([\w\d]+)$/);
            if (matchLetter && !getConfig(EXT_NAME).includes(matchLetter[0])) {
                console.log('match');
                return undefined;
            }
            hotReloadFn(str);
        }
    }
}